Object.defineProperty(exports, "__esModule", {
    value: !0
});
var e = Object.assign || function (e) {
            for (var t = 1; t < arguments.length; t++) {
                var o = arguments[t];
                for (var n in o) Object.prototype.hasOwnProperty.call(o, n) && (e[n] = o[n]);
            }
            return e;
        },
    t = require("../utils/request"),
    {domain} = require("../utils/env"),
    urlSu = (require("../utils/weApis"), getApp()),
    o = require("../utils/weApis"), n = (getApp(),
        getApp().globalData.channel);
/**
 * 支付成功通知服务端
 * @param outTradeNo  单号
 * @param transaction_id 交易ID
 * @param fee 支付金额
 * @returns {Promise}
 */
function notiServer(outTradeNo, transaction_id, fee) {
    return new Promise(function (resolve, reject) {
        wx.request({
          url: domain+'/order/paySuccess/' + outTradeNo + '/' + transaction_id + '/' + fee,
            header: {
                "content-type": "application/json"
            },
            method: "GET",
            data: {
                skey: wx.getStorageSync('skey')
            },
            success: function (res) {
                resolve(res);
            }
        })
    })

}
exports.notiServer = notiServer;
exports.bindGetUserInfo = function (e) {
    var o = e.detail;
    "getUserInfo:ok" === o.errMsg && t.login(o).then(function (e) {
        var o = getCurrentPages(), n = o[o.length - 1];
        n.setData({
            loginBgFlag: !1
        }), exports.getUserInfo(), n.onLoad(n.data.options || {}), wx.getStorageSync("userData");
    });
};

exports.payOrder = function (opt) {
    return new Promise(function (resolve, reject) {
            var o = t.lsGetObj("loginedUser");
            return wx.request({
              url: domain + (opt.url || "/pay/unifiedOrder"),
                header: {
                    "content-type": "application/json"
                },
                method: "GET",
                data: {
                    openid: o.openid,// open id
                    outTradeNo: opt.outTradeNo,
                    totalFee: floatTool.multiply(opt.payTotal, 100),//100
                    body: opt.body || '订单支付',
                    tradeType: 'JSAPI',
                    notifyURL: encodeURIComponent('https://min.taicanglimi.cn/api/wx-server-pay-notify'),
                },
                success: function (e) {
                    // 微信支付接口
                  if (!e.data.success){
                    return reject({
                      res: '支付失败,请稍后重试',
                      unitOrder: {}
                    })
                     console.log('支付失败')
                  }
                    var data = e.data.data;
                    var s = data.timeStamp, d = data.nonceStr,
                        r = data.package, i = data.paySign;
                    wx.requestPayment({
                        timeStamp: s,
                        nonceStr: d,
                        package: r,
                        signType: "MD5",
                        paySign: i,
                        success: function (e) {
                            wx.request({
                                url: domain+'pay/queryOrder',
                                header: {
                                    "content-type": "application/json"
                                },
                                method: "GET",
                                data: {
                                    outTradeNo: opt.outTradeNo,// open id
                                },
                                success: function (resData) {
                                    notiServer(opt.outTradeNo, resData.data.transactionId, opt.payTotal)
                                        .then(function (res1) {
                                            resolve({
                                                res: data,
                                                res1: res1,
                                                unitOrder: resData
                                            })
                                        });
                                },
                                fail: function (error) {
                                    reject({
                                        res: error,
                                        unitOrder: resData
                                    })
                                }
                            })
                        },
                        fail: function (a) {
                            reject({
                                res: a,
                            })
                        },
                        complete: function (a) {
                        }
                    });
                }
            })
        }
    )
};
exports.checkLogin = function () {
    var e = getCurrentPages(), t = e[e.length - 1];
  wx.getStorageSync("loginedUser") ? t.setData({
        loginBgFlag: !1
    }) : t.setData({
        loginBgFlag: !0
    });
};

exports.checkLoginAsyc = function () {
  var e = getCurrentPages(), t = e[e.length - 1];
  return new Promise((resolve,reject)=>{
    // debugger;
    if (wx.getStorageSync("loginedUser")){
      t.setData({
        loginBgFlag: !1
      })
      resolve(1)
    }else{
      t.setData({
        loginBgFlag: !0
      });
      reject(1)
    }
  })
  
};
exports.formatTime = function (data) {
    var date = new Date(data || Date.now());
    return date.getFullYear() + '-' + ((date.getMonth() + 1) > 9 ? (date.getMonth() + 1) : ('0' + (date.getMonth() + 1))) + '-' + (date.getDate() > 9 ? date.getDate() : ('0' + date.getDate())) +
        ' ' + date.getHours() + ":" + date.getMinutes();
}
exports.formatDate = function (data) {
    var date = new Date(data || Date.now());
    return date.getFullYear() + '-' + ((date.getMonth() + 1) > 9 ? (date.getMonth() + 1) : ('0' + (date.getMonth() + 1))) + '-' + (date.getDate() > 9 ? date.getDate() : ('0' + date.getDate()));
}
exports.addWXFormId = function (e) {
    var o = wx.getStorageSync("userData").skey || wx.getStorageSync("skey"),
        r = wx.getStorageSync("userData").phonetype || wx.getStorageSync("phoneType"), a = e.detail.formId;
    console.log(e, "formId"), a && "the formId is a mock one" != a && t.addWXFormId({
        skey: o,
        phonetype: r,
        channel: n,
        formId: a
    }).then(function (e) {
        return e;
    });
};
exports.getUserInfo = function () {
    o.getUserInfo().then(function (t) {
        var o = wx.getStorageSync("userData");
        if (typeof o == 'string') {
            o = JSON.parse(o);
        }
        wx.setStorageSync("userData", e({}, o, {
            userInfo: e({}, o.userInfo, t.userInfo)
        }));
    });
};
exports.toast = function (e, t, o) {
    if ("function" == typeof t && (o = arguments[1], t = 2e3), wx.showToast({
            title: e,
            icon: "none",
            duration: t || 2e3,
            mask: !0
        }), "function" == typeof o) {
        clearTimeout(n);
        var n = setTimeout(function () {
            o();
        }, t || 2e3);
    }
};
exports.onPullDownRefresh = function () {
    var e = getCurrentPages(), t = e[e.length - 1];
    setTimeout(function () {
        t.onLoad(t.data.options || {}), wx.stopPullDownRefresh();
    }, 1e3);
};
exports.showIndex = function () {
    var e = getCurrentPages(), t = e[e.length - 1];
    1 === e.length && t.setData({
        showGoIndex: !0
    });
};
exports.numberStrSort = function (a, b) {
    a = parseInt(a);
    b = parseInt(b);
    return a > b ? 1 : -1
};
exports.formatDate = function (needTime) {
    //needTime是整数，否则要parseInt转换
    var time = new Date(needTime);
    var y = time.getFullYear();
    var m = time.getMonth() + 1;
    var d = time.getDate();
    var h = time.getHours();
    var mm = time.getMinutes();
    var s = time.getSeconds();
    // return y+'-'+m+'-'+d+' '+h+':'+mm+':'+s;
    return y + '-' + m + '-' + d;
};

/**
 * floatTool 包含加减乘除四个方法，能确保浮点数运算不丢失精度
 *
 * 我们知道计算机编程语言里浮点数计算会存在精度丢失问题（或称舍入误差），其根本原因是二进制和实现位数限制有些数无法有限表示
 * 以下是十进制小数对应的二进制表示
 *      0.1 >> 0.0001 1001 1001 1001…（1001无限循环）
 *      0.2 >> 0.0011 0011 0011 0011…（0011无限循环）
 * 计算机里每种数据类型的存储是一个有限宽度，比如 JavaScript 使用 64 位存储数字类型，因此超出的会舍去。舍去的部分就是精度丢失的部分。
 *
 * ** method **
 *  add / subtract / multiply /divide
 *
 * ** explame **
 *  0.1 + 0.2 == 0.30000000000000004 （多了 0.00000000000004）
 *  0.2 + 0.4 == 0.6000000000000001  （多了 0.0000000000001）
 *  19.9 * 100 == 1989.9999999999998 （少了 0.0000000000002）
 *
 * floatObj.add(0.1, 0.2) >> 0.3
 * floatObj.multiply(19.9, 100) >> 1990
 *
 */

var floatTool = function () {

    /*
     * 判断obj是否为一个整数
     */
    function isInteger(obj) {
        return Math.floor(obj) === obj
    }

    /*
     * 将一个浮点数转成整数，返回整数和倍数。如 3.14 >> 314，倍数是 100
     * @param floatNum {number} 小数
     * @return {object}
     *   {times:100, num: 314}
     */
    function toInteger(floatNum) {
        var ret = {times: 1, num: 0}
        if (isInteger(floatNum)) {
            ret.num = floatNum
            return ret
        }
        var strfi = floatNum + ''
        var dotPos = strfi.indexOf('.')
        var len = strfi.substr(dotPos + 1).length
        var times = Math.pow(10, len);
        var isFu = floatNum < 0;
        var intNum = parseInt(Math.abs(floatNum) * times + 0.5, 10)
        ret.times = times
        if (isFu) {
            ret.num = -intNum
        } else {
            ret.num = intNum
        }

        return ret
    }

    /*
     * 核心方法，实现加减乘除运算，确保不丢失精度
     * 思路：把小数放大为整数（乘），进行算术运算，再缩小为小数（除）
     *
     * @param a {number} 运算数1
     * @param b {number} 运算数2
     * @param digits {number} 精度，保留的小数点数，比如 2, 即保留为两位小数
     * @param op {string} 运算类型，有加减乘除（add/subtract/multiply/divide）
     *
     */
    function operation(a, b, op) {
        var o1 = toInteger(a)
        var o2 = toInteger(b)
        var n1 = o1.num
        var n2 = o2.num
        var t1 = o1.times
        var t2 = o2.times
        var max = t1 > t2 ? t1 : t2
        var result = null
        switch (op) {
            case 'add':
                if (t1 === t2) { // 两个小数位数相同
                    result = n1 + n2
                } else if (t1 > t2) { // o1 小数位 大于 o2
                    result = n1 + n2 * (t1 / t2)
                } else { // o1 小数位 小于 o2
                    result = n1 * (t2 / t1) + n2
                }
                return result / max
            case 'subtract':
                if (t1 === t2) {
                    result = n1 - n2
                } else if (t1 > t2) {
                    result = n1 - n2 * (t1 / t2)
                } else {
                    result = n1 * (t2 / t1) - n2
                }
                return result / max
            case 'multiply':
                result = (n1 * n2) / (t1 * t2)
                return result
            case 'divide':
                return result = function () {
                    var r1 = n1 / n2
                    var r2 = t2 / t1
                    return operation(r1, r2, 'multiply')
                }()
        }
    }

    // 加减乘除的四个接口
    function add(a, b) {
        return operation(a, b, 'add')
    }

    function subtract(a, b) {
        return operation(a, b, 'subtract')
    }

    function multiply(a, b) {
        return operation(a, b, 'multiply')
    }

    function divide(a, b) {
        return operation(a, b, 'divide')
    }

    // exports
    return {
        add: add,
        subtract: subtract,
        multiply: multiply,
        divide: divide
    }
}();
exports.floatTool = floatTool;

